<?php 
/**
 *  Por Federico Pisarello - SisDev Software (c) 2012 - Buenos Aires, Argentina.
 * 	fpisarello@sisdevsoft.com
 */

require("includes/funciones.inc.php");

session_start();
if(!isset($_SESSION['userName']))
	exit();

function getDetailTableState()
{
	require("includes/constants.php");
	require("includes/datatables_db/Datatables.php");
	
	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	$strSQL = "SELECT * FROM orderfood WHERE idTable = ".$_REQUEST["idTable"]." ORDER BY idOrderFood DESC LIMIT 1";
	$rsOrderFood = $DB->Execute($strSQL);
	
	$idOrderFood = $rsOrderFood->fields("idOrderFood");
	$idTable = $_REQUEST["idTable"];
	
	$datatables = new Datatables();
	
	$datatables
			->select('description')
			->from('food')
			->join('orderfooditem','food.idFood = orderfooditem.idFood')
			->select('quantity, orderfooditem.price')
			->join('orderfood','orderfood.idOrderFood = orderfooditem.idOrderFood')
			->where("orderfood.idOrderFood = ".$idOrderFood)
			->where("orderfood.idTable = ".$idTable);
	
	$datatables->where("orderfood.idRestaurant = ".$_SESSION['userRestaurant']);

	return $datatables->generate();
}

function searchABMTables()
{
	require("includes/constants.php");
	require("includes/datatables_db/Datatables.php");
	
	$datatables = new Datatables();
	
	$datatables
			->select('idTable, description')
			->from('tables')
			->join('restaurant','tables.idRestaurant = restaurant.idRestaurant')
			->select('businessName')
			->where("tables.state <> '".$stateErase."'");
	if($_SESSION['userType'] != $idTypeAdministrator)
		$datatables->where("tables.idRestaurant = ".$_SESSION['userRestaurant']);

	return $datatables->generate();
}

function addOrEdit()
{
	require("includes/constants.php");
	require("includes/selectLanguage.php");

	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;

	$DB->StartTrans(); // start transaction
	
	if(!isset($_REQUEST["idTable"])){
					
		$strSQL = "INSERT INTO tables ( ";
		$strSQL .= "	description, ";
		$strSQL .= "	state, ";
		$strSQL .= "	idRestaurant ";
		$strSQL .= "	) VALUES ( ";
		$strSQL .= "	'".mb_strtoupper($_REQUEST["tableDescription"], "UTF-8")."', ";
		$strSQL .= "	'".$stateTableFree."', ";
		if($_SESSION['userType'] == $idTypeAdministrator)
			$strSQL .= "	'".$_REQUEST["cmbRestaurant"]."' ";
		else
			$strSQL .= "	'".$_SESSION['userRestaurant']."' ";
		$strSQL .= "	)";
	}
	else{
		$strSQL = "UPDATE tables SET ";
		$strSQL .= "	description = '".mb_strtoupper($_REQUEST["tableDescription"], "UTF-8")."', ";
		if($_SESSION['userType'] == $idTypeAdministrator)
			$strSQL .= "	idRestaurant = ".$_REQUEST["cmbRestaurant"];
		else
			$strSQL .= "	idRestaurant = ".$_SESSION['userRestaurant'];
		$strSQL .= " WHERE idTable = ". $_REQUEST["idTable"];
	}
	
	$DB->Execute($strSQL);
	
	if (!$DB->CompleteTrans())
	{
		$arrJSON->status = "ERROR";
		$arrJSON->msg = $a_languages['Common.ErrorGrabar'];
	}
	else
	{
		$arrJSON->status = "OK";
		$arrJSON->msg = $a_languages['Common.OkGrabar'];
	}	
	return json_encode($arrJSON);
}

function del()
{
	require("includes/constants.php");
	require("includes/selectLanguage.php");
	
	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	$DB->StartTrans(); // start transaction
	$DB->Execute("UPDATE tables SET state='$stateErase' WHERE idTable=" . $_REQUEST["idTable"]); // execute query

	if (!$DB->CompleteTrans())
	{
		$arrJSON->status = "ERROR";
		$arrJSON->msg = $a_languages['Common.ErrorEliminar'];
	}
	else
	{
		$arrJSON->status = "OK";
		$arrJSON->msg = $a_languages['Common.OkEliminar'];
	}	
	return json_encode($arrJSON);
}

function editTable()
{
	require("includes/constants.php");
		
	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	if($_SESSION['userType'] == $idTypeAdministrator)
		$rsTable = $DB->Execute("SELECT * FROM tables WHERE state <> '$stateErase' AND idTable=" . $_REQUEST["idTable"]); // execute query
	else
		$rsTable = $DB->Execute("SELECT * FROM tables WHERE state <> '$stateErase' AND idRestaurant = ".$_SESSION['userRestaurant']." AND idTable=" . $_REQUEST["idTable"]); // execute query
						
	if(!$rsTable->EOF){
		$joTables->data['tableDescription'] = $rsTable->fields("description");
		$joTables->data['idRestaurant'] = $rsTable->fields("idRestaurant");
		
		return json_encode($joTables->data);
	}
	else
		return json_encode(array());
}

function getRestaurants()
{
	require("includes/selectLanguage.php");

	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	$rsRestaurant = $DB->Execute("SELECT * FROM restaurant");
	
	$i=0;
	while(!$rsRestaurant->EOF){
		$arrRestaurant->data[$i]['idRestaurant'] = $rsRestaurant->fields(0);
		$arrRestaurant->data[$i++]['businessName'] = $rsRestaurant->fields(1);
		$rsRestaurant->MoveNext();
	}
	
	return json_encode($arrRestaurant->data);
}

function getTableState()
{
	require("includes/constants.php");
	require("includes/selectLanguage.php");
		
	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	$rsTable = $DB->Execute("SELECT * FROM tables WHERE state <> '$stateErase' AND idRestaurant = ".$_SESSION['userRestaurant']); // execute query

	if(!$rsTable->EOF){
		while(!$rsTable->EOF)
		{
			$joTables = "";
			$joTables->state = $rsTable->fields("state");
			$joTables->id = 'idTable'.$rsTable->fields("idTable");
			if($rsTable->fields("state") == $stateTableBusy || $rsTable->fields("state") == $stateTableClose)
			{
		    	$totalTable = 0;
		    	$sSQL = "SELECT * FROM orderfood WHERE idTable = ".$rsTable->fields(0)." AND state IN ('$stateTableBusy','$stateTableClose') ORDER BY idOrderFood DESC LIMIT 1";
				$rsTablesDescrip = $DB->Execute($sSQL);
				
				if(!$rsTablesDescrip->EOF && $rsTablesDescrip->fields('state') == $rsTable->fields("state"))
				{
					$joTables->guests = $a_languages['Init.Guests'].$rsTablesDescrip->fields('numGuests');
					
					$orderFood = $rsTablesDescrip->fields(0);
		        	$sSQL = "SELECT * FROM typemenufoods";
					$rsTablesDescrip = $DB->Execute($sSQL);
					$i=0;
					while (!$rsTablesDescrip->EOF){
						$sSQL = "SELECT SUM(o.quantity) can, SUM(o.price) pric FROM orderfooditem o ".
								"INNER JOIN food f ON f.idFood = o.idFood ".
								"INNER JOIN typefood t ON f.idTypeFood = t.idTypeFood ".
								"WHERE t.idMenuFood = ".$rsTablesDescrip->fields(0)." AND idOrderFood = ".$orderFood." AND quantity >= 0";
								
						$rsTablesDescripItem = $DB->Execute($sSQL);
						$joTables->items[$i++]['typeFoodDescription'] = $a_languages[$rsTablesDescrip->fields('description')].": ".(is_null($rsTablesDescripItem->fields(0)) ? 0 : $rsTablesDescripItem->fields(0));
						
						$totalTable += $rsTablesDescripItem->fields(1);
						
						$rsTablesDescrip->MoveNext();
					}
					$joTables->total = $a_languages['Init.Total'].'$ '.$totalTable;
				}
				else {
					$joTables->items[$i++]['typeFoodDescription'] = "";
					$joTables->total = "";
					$joTables->guests = "";
				}
			}
			else {
				$joTables->description = $a_languages['Init.StateTable'].$a_languages['Tables.FreeTable'];
			}
			
			$jaTables->tables[] = $joTables;
			$rsTable->MoveNext();
		}
		
		return json_encode($jaTables);
	}
	else
		return json_encode(array());
}

function setOpenTable()
{
	require("includes/constants.php");
	require("includes/selectLanguage.php");
	
	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	$DB->StartTrans(); // start transaction
	$DB->Execute("UPDATE tables SET state='$stateTableFree' WHERE state = '$stateTableClose' AND idTable=" . $_REQUEST["idTable"]); // execute query
	$DB->Execute("UPDATE orderfood SET state='$stateTableFree' WHERE state = '$stateTableClose' AND idTable=" . $_REQUEST["idTable"]); // execute query

	if (!$DB->CompleteTrans())
		$arrJSON->status = "ERROR";
	else
		$arrJSON->status = "OK";
	return json_encode($arrJSON);
}

switch($_REQUEST['actionOfForm'])
{
	case "EDIT":
		echo editTable();
		break;
	case "DELETE":
		echo del();
		break;
	case "search":
		echo searchABMTables();
		break;
	case "addOrEdit":
		echo addOrEdit();
		break;
	case "getRestaurants":
		echo getRestaurants();
		break;
	case "getTableState":
		echo getTableState();
		break;
	case "getDetailTableState":
		echo getDetailTableState();
		break;
	case "OPEN_TABLE":
		echo setOpenTable();
		break;
}
?>
